package com.yusvn.scm.admin.service;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.yusvn.scm.common.BaseService;
import com.yusvn.scm.common.kit.RetKit;
import com.yusvn.scm.common.model.SysDictionary;

/**
 * 系统字典管理
 * @author liugz
 *
 */
public class AdminDictService extends BaseService {

	SysDictionary dao = new SysDictionary().dao();
	
	public Page<SysDictionary> page(Kv kv) {
		Page<SysDictionary> list = dao.template("admin.dict.page", kv).paginate(getPage(kv), getLimit(kv));
		
		return list;
	}

	public SysDictionary get(Object idValue) {
		return dao.findById(idValue);
	}

	public List<SysDictionary> list() {
		//return dao.findAll();
		return dao.find("select * from sys_dictionary order by sort_number, dict_id ");
	}
	
	public boolean exists(int roleId, String name) {
		name = name.toLowerCase().trim();
		String sql = "select dict_id from sys_dictionary where (dict_name = ?) and dict_id != ? limit 1";
		Integer id = Db.queryInt(sql, name, roleId);
		return id != null;
	}
	
	public RetKit save(String jsonObj) {
		SysDictionary dict = JSON.parseObject(jsonObj, SysDictionary.class);
		
		if (exists(-1, dict.getDictName() )) {
			return RetKit.fail("名称已经存在，请输入别的名称");
		}
		
		dict.setDictName(dict.getDictName().trim());
		
		if(dict.save()) {
			return RetKit.ok("添加成功");
		}
		
		return RetKit.fail("添加失败");
	}

	public RetKit update(String jsonObj) {
		SysDictionary dict = JSON.parseObject(jsonObj, SysDictionary.class);
		
		if (exists(dict.getDictId(), dict.getDictName() )) {
			return RetKit.fail("名称已经存在，请输入别的名称");
		}
		
		dict.setDictName(dict.getDictName().trim());
		
		if(dict.update()) {
			return RetKit.ok("修改成功");
		}
		
		return RetKit.fail("修改失败");
	}

	public RetKit remove(String id) {
		if(dao.deleteById(id)) {
			return RetKit.ok("删除成功");
		}
		return RetKit.fail("删除失败");
	}

	public RetKit removeBatch(String idsStr) {
		JSONObject idsObj = JSON.parseObject(idsStr);
		JSONArray idsArr = idsObj.getJSONArray("ids");
		
		Object[][] paras = new Object[idsArr.size()][1];
		for(int i=0;i<idsArr.size();i++) {
			paras[i][0] = idsArr.get(i);
		}
		
		int[] cntArr = Db.batch("delete from sys_dictionary where dict_id=? ", paras, 100);
		
		int cntOk = 0;
		for(int i=0; i<cntArr.length; i++) {
			cntOk = cntOk + cntArr[i];
		}
		
		if(cntArr.length>0) {
			return RetKit.ok("成功删除 "+cntOk+" 条数据");
		}
		
		return RetKit.fail("批量删除失败");
	}
	
}
